package com.threefish.common.config;

import com.threefish.common.config.properties.ConfigProperties;
import com.threefish.common.config.properties.SysProperties;
import com.threefish.common.plugins.beetl.GlobalExt;
import com.threefish.common.plugins.beetl.ShiroExt;
import com.threefish.common.plugins.beetl.UtilsExt;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;
/**
 * @author 黄川 huchuc@vip.qq.com
 * @date: 2018/9/7
 */
@Configuration
public class BeetlConfig {

    @Value("${beetl.templatesPath}")
    private String templatesPath;

    @Autowired
    private SysProperties sysProperties;

    @Autowired
    private ConfigProperties configProperties;

    @Bean(name = "BeetlConf")
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
        BeetlGroupUtilConfiguration configuration = new BeetlGroupUtilConfiguration();
        //获取Spring Boot 的ClassLoader
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = BeetlConfig.class.getClassLoader();
        }
        ClasspathResourceLoader cploder = new ClasspathResourceLoader(loader, templatesPath);
        configuration.setResourceLoader(cploder);
        //额外的配置，可以覆盖默认配置
        Properties properties = new Properties();
        properties.setProperty("WEBAPP_EXT", GlobalExt.class.getName());
        configuration.setConfigProperties(properties);
        configuration.init();
        //如果使用了优化编译器，涉及到字节码操作，需要添加ClassLoader
        configuration.getGroupTemplate().setClassLoader(loader);
        configuration.getGroupTemplate().getSharedVars().put("props", System.getProperties());
        configuration.getGroupTemplate().getSharedVars().put("sys", sysProperties);
        configuration.getGroupTemplate().getSharedVars().put("cfg", configProperties);
        configuration.getGroupTemplate().registerFunctionPackage("so", new ShiroExt());
        configuration.getGroupTemplate().registerFunctionPackage("fn", new UtilsExt());
        return configuration;

    }

    @Bean(name = "beetlViewResolver")
    public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("BeetlConf") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) {
        BeetlSpringViewResolver viewResolver = new BeetlSpringViewResolver();
        viewResolver.setContentType("text/html;charset=UTF-8");
        viewResolver.setOrder(0);
        viewResolver.setConfig(beetlGroupUtilConfiguration);
        return viewResolver;
    }

}